import {
  ArgumentMetadata,
  BadRequestException,
  PipeTransform,
} from "@nestjs/common";
import { plainToInstance } from "class-transformer";
import { validate, ValidationError } from "class-validator";
export class ValidationPipe implements PipeTransform {
  async transform(value: any, { metatype }: ArgumentMetadata) {
    console.log(metatype, "metatype");
    console.log(value);
    if (!metatype || !this.needValidate(metatype)) {
      return value;
    }
    const instance = plainToInstance(metatype, value);
    const errors = await validate(instance);
    if (errors.length > 0) {
      throw new BadRequestException(this.formatErros(errors));
    }
    return value;
  }
  private needValidate(metatype: any): boolean {
    const types = [String, Boolean, Number, Array, Object];
    return !types.find((type) => metatype === type);
  }
  private formatErros(errors: ValidationError[]) {
    return errors
      .map((error) => {
        for (const key in error.constraints) {
          return error.constraints[key];
        }
      })
      .join(",");
  }
}
